package com.yuma.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuma.tingshu.album.mapper.*;
import com.yuma.tingshu.album.service.BaseCategoryService;
import com.yuma.tingshu.model.album.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private BaseAttributeMapper baseAttributeMapper;

    @Autowired
    private BaseAttributeValueMapper baseAttributeValueMapper;

    @Override
    public JSONObject getBaseCategoryList(Long category1Id) {
        List<BaseCategoryView> baseCategoryViews = this.baseCategoryViewMapper.selectList(new LambdaQueryWrapper<BaseCategoryView>().eq(BaseCategoryView::getCategory1Id, category1Id));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("categoryId", category1Id);
        jsonObject.put("categoryName", baseCategoryViews.get(0).getCategory1Name());

        JSONArray array2 = new JSONArray();
        Map<Long, List<BaseCategoryView>> category2Map = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
        category2Map.forEach((key, list2) -> {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("categoryId", list2.get(0).getCategory2Id());
            jsonObject1.put("categoryName", list2.get(0).getCategory2Name());

            JSONArray array3 = new JSONArray();
            list2.forEach(category3 -> {
                JSONObject object2 = new JSONObject();
                object2.put("categoryId", category3.getCategory3Id());
                object2.put("categoryName", category3.getCategory3Name());
                array3.add(object2);
            });
            jsonObject1.put("categoryChild", array3);
            array2.add(jsonObject1);
        });
        jsonObject.put("categoryChild", array2);
        return jsonObject;
    }

    @Override
    public BaseCategoryView getBaseCategoryViewByCategory3Id(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(new LambdaQueryWrapper<BaseCategoryView>().eq(BaseCategoryView::getCategory1Id, category1Id));

		List<Long> category3IdList = baseCategoryViewList.stream().map(BaseCategoryView::getCategory3Id).toList();

		return baseCategory3Mapper.selectList(new LambdaQueryWrapper<BaseCategory3>()
                .in(BaseCategory3::getId, category3IdList)
                .eq(BaseCategory3::getIsTop, 1)
                .select(BaseCategory3::getId, BaseCategory3::getName)
                .last("limit 7"));
    }

    public List<BaseAttribute> findAttribute2(Long category1Id) {
        List<BaseAttribute> baseAttributeList = baseAttributeMapper.selectList(new LambdaQueryWrapper<BaseAttribute>().eq(BaseAttribute::getCategory1Id, category1Id));
        baseAttributeList.forEach((baseAttribute) -> {
            List<BaseAttributeValue> baseAttributeValueList = baseAttributeValueMapper.selectList(new LambdaQueryWrapper<BaseAttributeValue>().eq(BaseAttributeValue::getAttributeId, baseAttribute.getId()));
            baseAttribute.setAttributeValueList(baseAttributeValueList);
        });
        return baseAttributeList;
    }

    @Override
    public List<BaseAttribute> findAttribute(Long category1Id) {
        return baseAttributeMapper.findAttribute(category1Id);
    }

    /**
     * 方案1：多次单表查询
     * 缺点：数据库太累，效率低
     * 方案2：一次多表查询
     * <p>
     * 方案3：引入视图,还是方案2
     *
     * @return
     */
    @Override
    public List<JSONObject> getBaseCategoryList() {

        List<JSONObject> list1 = new ArrayList<>();
        // 查询分类视图，获取包含所有三级分类信息的数据
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        // 将所有的一级分类存入List<JSONObject> list1
        // 思路:将baseCategoryViewsList转换成Map，key1是一级标题的id，value1是该一级标题id对应的所有BaseCategoryView组成的LIST 分析见图1.1
        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        category1Map.forEach((key1, value1) -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("categoryId", key1);
            jsonObject.put("categoryName", value1.get(0).getCategory1Name());

            // 将所有的二级分类存入List<JSONObject> list2
            List<JSONObject> list2 = new ArrayList<>();
            // 对value1这是一个list,转换为map,key2是二级分类id,value2是该二级分类id对应的view list
            Map<Long, List<BaseCategoryView>> category2Map = value1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            category2Map.forEach((key2, value2) -> {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("categoryId", key2);
                jsonObject2.put("categoryName", value2.get(0).getCategory2Name());

                // 将所有的三级分类存入List<JSONObject> list3
                List<JSONObject> list3 = new ArrayList<>();
                // 对value2这是一个list,转换为map,key3是二级分类id,value3是该二级分类id对应的view list
//				Map<Long, List<BaseCategoryView>> category3Map = value2.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory3Id));
                value2.forEach((value3) -> {
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("categoryId", value3.getCategory3Id());
                    jsonObject3.put("categoryName", value3.getCategory3Name());
                    list3.add(jsonObject3);
                });
                jsonObject2.put("categoryChild", list3);
                list2.add(jsonObject2);
            });
            jsonObject.put("categoryChild", list2);
            list1.add(jsonObject);
        });
        return list1;
    }

    /**
     * [
     * {
     * "categoryId":1,                       #一级分类ID
     * "categoryName":"图书、音像、电子书刊",   #一级分类名称
     * "categoryChild":[                     #当前一级分类包含的二级分类集合
     * {
     * "categoryId":1,               #二级分类ID
     * "categoryName":"电子书刊",     #二级分类名称
     * "categoryChild":[             #当前二级分类包含的三级分类集合
     * {
     * "categoryId":1         #三级分类ID
     * "categoryName":"电子书",#三级分类名称
     * },
     * {
     * "categoryId":2,
     * "categoryName":"网络原创"
     * }
     * ]
     * }
     * ]
     * },
     * ...
     * ]
     */
    public List<JSONObject> getBaseCategoryList1() {
        List<JSONObject> list1 = new ArrayList<>();
        //1. 查询一级分类并放入list1中
        List<BaseCategory1> category1List = baseCategory1Mapper.selectList(null);
        category1List.forEach(category1 -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("categoryId", category1.getId());
            jsonObject.put("categoryName", category1.getName());

            List<JSONObject> list2 = new ArrayList<>();
            //2. 查询二级分类并放入list2中
            List<BaseCategory2> category2List = baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1.getId()));
            category2List.forEach(category2 -> {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("categoryId", category2.getId());
                jsonObject2.put("categoryName", category2.getName());

                List<JSONObject> list3 = new ArrayList<>();
                //3. 查询三级分类并放入list3中
                List<BaseCategory3> category3List = baseCategory3Mapper.selectList(new LambdaQueryWrapper<BaseCategory3>().eq(BaseCategory3::getCategory2Id, category2.getId()));
                category3List.forEach(category3 -> {
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("categoryId", category3.getId());
                    jsonObject3.put("categoryName", category3.getName());
                    list3.add(jsonObject3);
                });
                jsonObject2.put("categoryChild", list3);
                list2.add(jsonObject2);
            });
            jsonObject.put("categoryChild", list2);
            list1.add(jsonObject);
        });
        return list1;
    }


}
